<template>
  <view class="table" :style="[getTableStyle]" :class="{ 'is-border': border, 'no-data': data.length === 0 }">
    <view class="table_inner">
      <view class="table_header" v-if="showHeader">
        <view class="b_table" :style="[tableBodyStyle]">
          <view class="b_thead">
            <view class="b_tr" :class="[getHeaderClass]" :style="[getHeaderStyle]" @click="handleHeaderClick">
              <view class="b_th" v-if="indexShow" :style="[getIndexColStyle]">
                <!-- style="min-width: 52px;text-align: center;" -->
                <view class="b_cell">序号</view>
              </view>
              <view class="b_th" v-for="item in columns" :key="item.fieldKey" :class="[getCellProps(item).class]"
                :style="[getCellProps(item).style]">
                <view class="b_cell">{{ item.fieldTitle }}</view>
              </view>
            </view>
          </view>
        </view>
      </view>
      <view class="table_body">
        <view class="b_table" :style="[tableBodyStyle]">
          <view class="b_tbody" v-if="data.length > 0">
            <view class="b_tr" v-for="(scope, index) in data" :key="index" :class="[getBodyClass(scope, index)]"
              :style="[getBodyStyle(scope, index)]" @click="handleRowClick(scope, index)">
              <view class="b_td" v-if="indexShow" :style="[getIndexColStyle]">
                <view class="b-cell">{{ getIndexMethod(index) }}</view>
              </view>
              <view class="b_td text-cut ellipsis" v-for="(column, columnIndex) in columns" :key="column.fieldKey"
                :class="[getCellProps(column).class]" :style="[getCellProps(column).style]"
                @click="onClick(scope, column)">
                <view class="b_cell text-cut ellipsis" @click.stop="handleCellClick(scope, column, index, columnIndex)"
                  :style="[getCellStyle(scope, index, columnIndex)]">
                  <!-- <slot name="item" :index="index"  :scope="scope"
                    :column="column">
                    {{ scope }}
                </slot> -->
                  <slot name="item" :index="index" :scope="scope" :column="column" v-if="column.fieldType === 'slot'">
                  </slot>
                  <view v-else>{{ scope[column.fieldKey] }}</view>
                </view>
              </view>
            </view>
          </view>
          <view class="table_empty" v-else>
            <u-empty v-if="!$slots.empty" :text="emptyText"></u-empty>
            <slot name="empty"></slot>
          </view>
        </view>
      </view>
      <!-- <view class="table_footer">底部</view> -->
    </view>
  </view>
</template>
<script>
export default {
  props: {
    // 获取列数据
    columns: {
      type: Array,
      default: () => []
    },
    // 获取表格数据
    data: {
      type: Array,
      default: () => []
    },
    // 对齐方式
    align: {
      type: String,
      default: 'left'
    },
    // 高度
    height: {
      type: String
    },
    // 最高高度
    maxHeight: {
      type: String
    },
    // 宽度
    width: {
      type: String,
      default: '100%'
    },
    // 空数据
    emptyText: {
      type: String,
      default: '暂无数据'
    },
    // 是否设置边框
    border: {
      type: Boolean,
      default: false
    },
    // 斑马纹配置
    stripe: {
      type: Boolean,
      default: false
    },
    // 显示表头
    showHeader: {
      type: Boolean,
      default: true
    },
    // 显示底部
    // showFooter: {
    // 	type: Boolean,
    // 	default: false
    // },
    // footerMethod: {
    // 	type: Function
    // },
    // footerText: {
    // 	type: String,
    // 	default: '合计'
    // },
    // 显示序号
    indexShow: {
      type: Boolean,
      default: false
    },
    // 最小宽度
    minItemWidth: {
      type: Number,
      default: 52
    },
    // 增加行类名
    rowClassName: {
      type: [Function, String]
    },
    // 增加行样式
    rowStyle: {
      type: [Function, Object]
    },
    // 单元格样式
    cellStyle: {
      type: [Function, Object]
    },
    // 自定义序号
    indexMethod: {
      type: Function
    },
    // 头类名
    headerRowClassName: {
      type: String
    },
    // 头部样式
    headerRowStyle: {
      type: Object
    },
    // 宽度
    indexWidth: {
      type: String,
      default: '53px'
    }
  },
  data() {
    return {
      sumList: [],
      tableWidth: 0
    }
  },
  mounted() {
    // 获取表格宽度
    const query = uni
      .createSelectorQuery()
      .in(this)
      .select('.table')
    query
      .boundingClientRect(data => {
        this.tableWidth = data.width
      })
      .exec()
  },
  computed: {
    // 表格样式
    getTableStyle() {
      const { width, height, maxHeight } = this
      const tableStyle = {}
      if (width) {
        tableStyle.width = width
      }
      if (height) {
        tableStyle.height = height
      }
      if (maxHeight) {
        tableStyle.maxHeight = maxHeight
      }
      return tableStyle
    },
    // 头部和主体样式
    tableBodyStyle() {
      if (!this.tableWidth) return {}
      const clienWidth = this.tableWidth
      // 筛选没有宽度的
      const flexColumn = this.columns.filter(item => !item.width)
      const minWidth = this.minItemWidth

      // 计算宽度累加
      let bodyMinWidth = this.columns.reduce((t, c) => {
        c.width = c.width || minWidth
        return t + parseFloat(c.width)
      }, 0)
      // 判断是否需要序号
      if (this.indexShow) {
        bodyMinWidth += parseFloat(this.indexWidth)
      }
      // console.log('body2', bodyMinWidth)
      if (flexColumn.length > 0 && bodyMinWidth < clienWidth) {
        const flexWidth = clienWidth - bodyMinWidth
        if (flexColumn.length === 1) {
          flexColumn[0].width = minWidth + flexWidth
        } else {
          const scaleWidth = flexWidth / flexColumn.length
          flexColumn.forEach(item => {
            item.width = minWidth + Math.floor(scaleWidth)
          })
        }
      }
      // if (flexColumn.length > 0 && bodyMinWidth > clienWidth) {
      // 	const flexWidth = bodyMinWidth - clienWidth;
      // 	if (flexColumn.length === 1) {
      // 		flexColumn[0].width = minWidth - flexWidth;
      // 	} else {
      // 		const scaleWidth = flexWidth / flexColumn.length;
      // 		flexColumn.forEach(item => {
      // 			item.width = minWidth - Math.floor(scaleWidth);
      // 		});
      // 	}
      //     // console.log(bodyMinWidth);
      //     // console.log(clienWidth);
      //     bodyMinWidth = clienWidth;
      //     // console.log(bodyMinWidth);
      // }
      // console.log('11',flexColumn);
      // console.log(this.columns);
      bodyMinWidth = Math.max(bodyMinWidth, clienWidth)
      return {
        width: `${bodyMinWidth}px`
      }
    },
    // 表头类名
    getHeaderClass() {
      const headerClass = []
      if (this.headerRowClassName) {
        headerClass.push(this.headerRowClassName)
      }
      return headerClass
    },
    // 表头样式
    getHeaderStyle() {
      const headerStyle = []
      if (typeof this.headerRowStyle === 'object') {
        if (this.headerRowStyle) {
          headerStyle.push(this.headerRowStyle)
        }
      }
      return headerStyle[0]
    },
    // 需要序号时样式
    getIndexColStyle() {
      return {
        textAlign: 'center',
        width: this.indexWidth
      }
    },
    showXScroll() {
      const clienWidth = this.tableWidth
      return clienWidth < parseFloat(this.tableBodyStyle?.width || 0)
    },
    isEmpty() {
      return this.data.length === 0
    }
  },
  methods: {
    handleHeaderClick() {
      console.log('点击表头')
    },
    handleRowClick(scope, index) {
      // 行数据响应
      this.$emit('row-click', scope, index)
    },
    onClick(scope, column) {
      console.log(scope, column, 6666)
    },
    handleCellClick(scope, column, index, columnIndex) {
      // console.log('点击单元格');
      // 单元格数据响应
      this.$emit('cell-click', { scope, column, index, columnIndex })
    },
    // 配置表格数据样式
    getBodyClass(scope, index) {
      const bodyClass = []
      if (this.stripe) {
        if (index % 2 === 1) bodyClass.push('is_stripe')
        // bodyClass.push({ 'is_stripe': index % 2 === 1 });
      }
      if (typeof this.rowClassName === 'function') {
        const rowClass = this.rowClassName?.(scope, index)
        if (rowClass) {
          bodyClass.push(rowClass)
        }
      } else if (typeof this.rowClassName === 'string') {
        if (this.rowClassName) {
          bodyClass.push(this.rowClassName)
        }
      }
      return bodyClass
    },

    getBodyStyle(scope, index) {
      const bodyStyle = []
      if (typeof this.rowStyle === 'function') {
        const rowStyle = this.rowStyle?.(scope, index)
        if (rowStyle) {
          bodyStyle.push(rowStyle)
        }
      } else if (typeof this.rowStyle === 'object') {
        if (this.rowStyle) {
          bodyStyle.push(this.rowStyle)
        }
      }
      return bodyStyle[0]
    },
    getCellStyle(scope, index, columnIndex) {
      const bodyStyle = []
      if (typeof this.cellStyle === 'function') {
        const cellStyle = this.cellStyle?.(scope, index, columnIndex)
        if (cellStyle) {
          bodyStyle.push(cellStyle)
        }
      } else if (typeof this.cellStyle === 'object') {
        if (this.cellStyle) {
          bodyStyle.push(this.cellStyle)
        }
      }
      return bodyStyle[0]
    },
    getIndexMethod(index) {
      let curIndex = index + 1
      if (typeof this.indexMethod === 'function') {
        curIndex = this.indexMethod?.(index)
      }
      return curIndex
    },
    // 固定列
    getCellProps(row) {
      const classList = []
      if (this.showXScroll && row.fixed) {
        classList.push('fixed')
        if (row.fixed === 'left') {
          classList.push('fixed-left')
        } else {
          classList.push('fixed-right')
        }
      }
      return {
        class: classList,
        style: {
          width: `${row.width}px`,
          textAlign: this.align,
          minWidth: `${this.minItemWidth}px`
        }
      }
    }
  }
}
</script>
<style lang="scss" scoped>
$bg-base-color: #ffffff;
$header-color: #909399;
$footer-bg-color: #f5f7fa;
$table-border: #edeeee;
$table-stripe-color: #fafafa;

.tt {
  background-color: skyblue;
}

.table {
  overflow: visible;

  // box-sizing: border-box;
  // box-sizing: content-box;
  &.is-border {
    border: 1px solid $table-border;
    border-bottom: none;
    border-top: none;

    .table_header {
      border-top: 1px solid $table-border;
    }
  }

  &.no-data {
    .base-table-body {
      border-bottom: 1px solid $table-border;
    }
  }

  .table_inner {
    display: flex;
    height: 100%;
    flex-direction: column;

    .table_header {
      width: 100%;
      flex-shrink: 0;
      position: sticky;
      z-index: 3;
    }

    .table_header {
      top: 0;
      // border-top: 1px solid $table-border;
    }

    .table_body {
      position: relative;
      flex: 1;
    }

    .b_table {
      display: table;
      table-layout: fixed;

      .b_thead {
        color: $header-color;
        table-layout: fixed;
        display: table-header-group;
        vertical-align: middle;
        font-weight: 700;
      }

      .b_tbody {
        display: table-row-group;
        vertical-align: middle;
        table-layout: fixed;
      }

      .b_tr {
        background-color: $bg-base-color;
        display: table-row;

        &.is_stripe {
          .b_td {
            background-color: $table-stripe-color;
            // background-color: red;
          }
        }
      }

      .b_th,
      .b_td {
        font-size: 28rpx;
        display: table-cell;
        border-bottom: 1px solid $table-border;
        padding: 8px 0;
        box-sizing: border-box;
        // overflow: hidden;
        // white-space: nowrap;
        // text-overflow: ellipsis;
        position: relative;
        vertical-align: middle;
        text-align: left;
        z-index: 1;

        .b_cell {
          box-sizing: border-box;
          //     overflow: hidden;
          // white-space: nowrap;
          // text-overflow: ellipsis;
          line-height: 23px;
          padding: 0 10px;
        }

        &.fixed {
          position: sticky !important;
          z-index: 2;
          background: $bg-base-color;
          border-right: 0;

          &::before {
            content: '';
            position: absolute;
            top: 0px;
            width: 10px;
            bottom: -1px;
          }
        }

        &.fixed_left {
          left: 0;

          &::before {
            right: -10px;
            box-shadow: inset 10px 0 10px -10px rgba(0, 0, 0, 0.15);
          }
        }

        &.fixed_right {
          right: 0;

          &::before {
            left: -10px;
            box-shadow: inset -10px 0 10px -10px rgba(0, 0, 0, 0.15);
          }
        }
      }

      .table_empty {
        min-height: 120rpx;
        line-height: 120rpx;
        width: 100%;
        text-align: center;
        color: $header-color;
        font-size: 24rpx;
        margin-top: 120rpx;
      }
    }
  }
}
</style>